package com.gate.ws.spring.network.handler;

import cn.hutool.json.JSONUtil;
import com.gate.ws.spring.constants.ChannelConstants;
import com.gate.ws.spring.process.upmsg.PackageProcessFactory;
import com.gate.ws.spring.process.upmsg.PacketProcessor;
import com.gate.ws.spring.service.MqSender;
import com.nami.basic.constants.UpTopicConst;
import com.nami.basic.packet.Packet;
import com.nami.basic.request.upmsg.ChannelCloseMqWrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.dromara.common.core.utils.SpringUtils;
import org.jetbrains.annotations.NotNull;


/**
 * 描述：
 *
 * @Author: lbc
 * @Date: 2023-07-14 15:38
 * @email: 594599620@qq.com
 * @Description: keep coding
 */
@Slf4j
public class NettyServerHandler extends SimpleChannelInboundHandler<Packet> {

    private PackageProcessFactory processFactory;

    public NettyServerHandler(PackageProcessFactory processFactory) {
        this.processFactory = processFactory;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("客户端握手成功，[{}]通道激活. 准备认证！", ctx.channel().remoteAddress());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        try {
            Channel channel = ctx.channel();
            String userId = (String) channel.attr(AttributeKey.valueOf(ChannelConstants.USER_ID)).get();
            if (StringUtils.isNotBlank(userId)) {
                MqSender mqSender = SpringUtils.getBean(MqSender.class);
                mqSender.send(UpTopicConst.CONNECT_TIMEOUT_TOPIC, JSONUtil.toJsonStr(newChannelCloseMsg(channel)));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.channelInactive(ctx);
    }

    @NotNull
    private static ChannelCloseMqWrap newChannelCloseMsg(Channel channel) {
        ChannelCloseMqWrap channelInactiveDTO = new ChannelCloseMqWrap();
        channelInactiveDTO.setUserId((String) channel.attr(AttributeKey.valueOf(ChannelConstants.USER_ID)).get());
        channelInactiveDTO.setAppKey((String) channel.attr(AttributeKey.valueOf(ChannelConstants.APP_KEY)).get());
        channelInactiveDTO.setDeviceType((Integer) channel.attr(AttributeKey.valueOf(ChannelConstants.DEVICE_TYPE)).get());
        log.info("[inactive] request={}", JSONUtil.toJsonStr(channelInactiveDTO));
        return channelInactiveDTO;
    }


//    @Override
//    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
//        cause.printStackTrace();
//        log.error("[nami-ws] 通道【{}】即将关闭 error:{}", ctx.channel().remoteAddress(), cause.getMessage());
//        // todo remove channel
//        log.info("[nami-ws] 剩余通道个数：{}", LocalChannelCache.USER_CHANNEL.size());
//    }

    @Override
    protected void channelRead0(ChannelHandlerContext context, Packet packet) throws Exception {
        PacketProcessor messageProcess = processFactory.getMessageProcess(packet.getCmd());
        messageProcess.process(context.channel(), packet);
    }

}
